package com.mego.maq.activitys;


import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.mego.maq.BuildConfig;
import com.mego.maq.R;
import com.mego.maq.adapter.DemoAdapter;
import com.mego.maq.database.dbmodel.Commandlog;
import com.mego.maq.database.dbmodel.SystemAllInfo;
import com.mego.maq.database.manager.CommandlogCenter;
import com.mego.maq.database.manager.SystemCenter;
import com.mego.maq.utils.GPSProvider;
import com.mego.maq.utils.LonLat;
import com.mego.maq.utils.Utils;
import com.mego.maq.version.UpdateManager;
import com.zxing.encoding.EncodingHandler;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.base.BaseListActivity;
import zuo.biao.library.interfaces.AdapterCallBack;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.ItemDialog;
import zuo.biao.library.util.MD5Util;

public class MainActivity extends BaseListActivity<Entry<Integer, String>, ListView, DemoAdapter> implements View.OnClickListener, ItemDialog.OnDialogItemClickListener, AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener, UpdateManager.InstallCallBack {


    private final String TAG = "MainActivity";
    public static final String INTENT_RANGE = "INTENT_RANGE";
    public static final String RESULT_CLICKED_ITEM = "RESULT_CLICKED_ITEM";

    public static Intent createIntent(Context context) {
        return new Intent(context, MainActivity.class);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

//        intent = getIntent();
//        range = intent.getIntExtra(INTENT_RANGE, range);

        //apk版本升级
        UpdateManager.getUpdateManager().checkAppUpdate(this, this, false);
        GPSProvider.getInstance().initGPSProvider(this);

//        CommandlogCenter.getInstance().addDemodata();

        initView();
        initData();
        initEvent();

        onReset();
        onRefresh();

    }

    void onReset() {
        if (ct != null) {
            ct.interrupt();
            ct = null;
        }
        ct = new ConnectThread();
        ct.start();
    }

    private ImageView ivPayQRCode;

    private TextView tvLLstr;
    private ConnectThread ct = null;

    @Override
    public void initView() {
        super.initView();

        _mobile = getDeviceId();

        TextView tv_devicenumber = (TextView) findView(R.id.tv_devicenumber);
        tv_devicenumber.setText("装置号码：" + _mobile);

        tvLLstr = (TextView) findView(R.id.tvLLstr);

        ivPayQRCode = findView(R.id.ivPayQRCode);
        setQRCode();

    }

    @Override
    public void setList(final List<Entry<Integer, String>> list) {
        setList(new AdapterCallBack<DemoAdapter>() {

            @Override
            public void refreshAdapter() {
                adapter.refresh(list);
            }

            @Override
            public DemoAdapter createAdapter() {
                return new DemoAdapter(context);
            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        tvBaseTitle.setText("正牌飞鸽");

//        showShortToast("正牌飞鸽");

        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    @Override
    public void getListAsync(int page) {
        showProgressDialog(R.string.loading);
        CommandlogCenter.getInstance().doQueryAll();
        ArrayList<Commandlog> commandlogList = CommandlogCenter.getInstance().getCommandlogList();
        List<Entry<Integer, String>> list = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < commandlogList.size(); i++) {
            list.add(new Entry<Integer, String>(i, commandlogList.get(i).getTitle()));
        }

        onLoadSucceed(page, list);
    }

    @Override
    public void initEvent() {

        super.initEvent();

        //如果adapter类型是zuo.biao.library.base.BaseAdapter，这两句就不用写了
        lvBaseList.setOnItemClickListener(this);
        lvBaseList.setOnItemLongClickListener(this);

        findViewById(R.id.tv_exit).setOnClickListener(this);

        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    public void onForwardClick(View v) {

    }

    //示例代码：ItemView点击和长按事件处理 <<<<<<<<<<<<<<<<<<<
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        showShortToast("选择了 " + adapter.getItem(position).getValue());
//        setResult(RESULT_OK, new Intent().putExtra(RESULT_CLICKED_ITEM, position));
//        finish();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        showShortToast("长按了 " + position);
        return true;
    }
    //示例代码：ItemView点击和长按事件处理 >>>>>>>>>>>>>>>>>>>

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_exit:
//                onExit();
                moveTaskToBack(true); //Activity不销毁，直接进入后台
                break;

        }
    }

    private long firstTime = 0;//第一次返回按钮计时

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                break;
            case KeyEvent.KEYCODE_BACK:
                onExit();
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    void onExit() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            showShortToast(getString(R.string.texit));
            firstTime = secondTime;
        } else {//完全退出
            moveTaskToBack(false);//应用退到后台
            System.exit(0);
        }

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }
        if (requestCode == 100) {

        }
    }

    @Override
    public void onDialogItemClick(int requestCode, int position, String item) {

    }

    ProgressDialog mPB;
    public static final int INITFINISH = 1101;
    public static final int FINISHSEND = 607;
    public static final int REFRESHLIST = 608;
    public static final int KAIJI = 609;
    public static final int GUANJI = 610;
    public static final int SHOWLLSTR = 611;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == INITFINISH) {
                if (mPB != null) {
                    mPB.dismiss();
                    mPB = null;
                }
            } else if (msg.what == FINISHSEND) {
                showShortToast("已经发送！");
            } else if (msg.what == REFRESHLIST) {
                showShortToast("收到新指令！");
                onRefresh();
            } else if (msg.what == KAIJI) {
                onReset();
                showShortToast("已重新开启连接！");

            } else if (msg.what == GUANJI) {
                if (ct != null) {
                    try {
                        ct.socket.close();
                        ct.interrupt();
                        ct = null;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                showShortToast("已断开连接！");

            } else if (msg.what == SHOWLLSTR) {
                LonLat pos = GPSProvider.getInstance().getPos();
                String strLL = pos.GetLon() + " " + pos.GetLat();
                tvLLstr.setText(strLL);
            }
        }
    };

    private final int REQUEST_TO_DOPAY = 25;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_TO_DOPAY:
                break;
        }
    }

    @Override
    public void onTimerStart() {

    }

    int _num = 0;

    @Override
    public void onTimerRefresh() {
        onSend();

        if (CommandlogCenter.getInstance().needGj()) {
            mHandler.sendEmptyMessage(GUANJI);
        }

        if (CommandlogCenter.getInstance().needKj()) {
            mHandler.sendEmptyMessage(KAIJI);
        }

        mHandler.sendEmptyMessage(SHOWLLSTR);
    }

    @Override
    public void onTimerStop() {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
        super.onDestroy();
    }

    private String getDeviceId() {

        SystemAllInfo info = SystemCenter.getInstance().getSysInfo("SERIAL");
        if (info == null) {
            //自动生成IMEI
            String code = Build.SERIAL;
            if (code.isEmpty() || code.compareToIgnoreCase("unknown") == 0) {
                code = MD5Util.MD5(System.currentTimeMillis() + Build.PRODUCT);
            }
            int max = 15;
            int size = code.length();
            if (size < max) {
                for (int i = size; i < max; i++) {
                    code += "0";
                }
            } else if (size > max) {
                code = code.substring(size - max);
            }
            info = new SystemAllInfo(null, "SERIAL", code.toLowerCase());
            SystemCenter.getInstance().saveSysInfo(info);
        }

        return info.getContent();
    }

    /**
     * 显示二维码
     */
    private Bitmap qRCodeBitmap;
    private String _mobile = "13564508883";

    protected void setQRCode() {

        if (mPB != null) {
            return;
        }

        mPB = ProgressDialog.show(this, "正在刷新设备二维码", "刷新中...");
        runThread(TAG + "setQRCode", new Runnable() {

            @Override
            public void run() {

                try {
                    int widthAndHeight = Utils.dip2px(MainActivity.this, 180);
                    qRCodeBitmap = EncodingHandler.createQRCode(_mobile, widthAndHeight);
                } catch (WriterException e) {
                    e.printStackTrace();
                }

                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ivPayQRCode.setImageBitmap(qRCodeBitmap);
                        mHandler.sendEmptyMessage(INITFINISH);
                    }
                });
            }
        });
    }

    String _msg = "";

    public void onSend() {
        //网络请求必需用线程
        new Thread(new Runnable() {
            @Override
            public void run() {

                //全数采集保存数据
                CommandlogCenter.getInstance().saveLonlatlogOne();
                //发送数据
                try {
                    if (ct != null) {
                        String msg = CommandlogCenter.getInstance().getSendmsg0(_mobile);
                        if (msg.length() > 1) {
                            ct.outputStream.write(msg.getBytes());
                            mHandler.sendEmptyMessage(FINISHSEND);
                        }
                        msg = CommandlogCenter.getInstance().getSendmsg2(_mobile);
                        if (msg.length() > 1) {
                            ct.outputStream.write(msg.getBytes());
                            mHandler.sendEmptyMessage(FINISHSEND);
                        }
                        msg = CommandlogCenter.getInstance().getSendmsg3(_mobile);
                        if (msg.length() > 1) {
                            ct.outputStream.write(msg.getBytes());
                            mHandler.sendEmptyMessage(FINISHSEND);
                        }
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();

    }

    class ConnectThread extends Thread {
        public Socket socket = null;        //定义socket
        public OutputStream outputStream = null;    //定义输出流（发送）
        public InputStream inputStream = null;    //定义输入流（接收）

        public void run() {
            try {
                socket = new Socket("106.14.209.254", 8902);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //获取输出流
            try {
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                while (true) {
                    final byte[] buffer = new byte[1024];//创建接收缓冲区
                    if (socket.isClosed()) {
                        return;
                    }
                    inputStream = socket.getInputStream();
                    final int len = inputStream.read(buffer);//数据读出来，并且返回数据的长度
                    _msg = CommandlogCenter.getInstance().saveCommandlog(new String(buffer, 0, len), _mobile);
                    if (_msg.length() > 1) {
                        outputStream.write(_msg.getBytes());
                    }

                    runOnUiThread(new Runnable()//不允许其他线程直接操作组件，用提供的此方法可以
                    {
                        public void run() {
                            mHandler.sendEmptyMessage(REFRESHLIST);
                        }
                    });
                }
            } catch (IOException e) {

            }

        }
    }


    //<--- 安装apk---
    String apkpath = "";//Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mego/Megoandroid_4.apk";

    void installAPK(String filePath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            /* Android N 写法*/
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", new File(apkpath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            /* Android N之前的老版本写法*/
            intent.setDataAndType(Uri.fromFile(new File(apkpath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            installAPK(apkpath);
        }
    }

    @Override
    public void doInstall(String filePath) {

        apkpath = filePath;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                installAPK(apkpath);
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }
    //---安装apk--->

}

//https://www.jianshu.com/p/791ee473a89b
//图片加载用Glide
//    $GPRMC,<1>,<2>,<3>,<4>,<5>,<6>,<7>,<8>,<9>,<10>,<11>,<12>*hh
//<1> UTC时间，hhmmss.sss(时分秒.毫秒)格式
//<2> 定位状态，A=有效定位，V=无效定位
//<3> 纬度ddmm.mmmm(度分)格式(前面的0也将被传输)
//<4> 纬度半球N(北半球)或S(南半球)
//<5> 经度dddmm.mmmm(度分)格式(前面的0也将被传输)
//<6> 经度半球E(东经)或W(西经)
//<7> 地面速率(000.0~999.9节，前面的0也将被传输)
//<8> 地面航向(000.0~359.9度，以正北为参考基准，前面的0也将被传输)
//<9> UTC日期，ddmmyy(日月年)格式
//<10> 磁偏角(000.0~180.0度，前面的0也将被传输)